package qiniu.voidcepc.voicepc.demos.web.utils.Log.Aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
public class ExecutionTimeAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExecutionTimeAspect.class);

    @Pointcut("@annotation(qiniu.voidcepc.voicepc.demos.web.utils.Log.TimeLog)")
    public void timeLogAspect(){}

    @Around("timeLogAspect()")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        // 获取方法信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getDeclaringClass().getName() + "." + method.getName();
        
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        
        // 执行目标方法
        Object result = null;
        try {
            result = joinPoint.proceed();
            return result;
        } finally {
            // 计算执行时间
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            
            // 记录日志
           LOGGER.info(() -> String.format("方法 [%s] 执行用时为 %d ms ,并且使用一下参数: %s",
               methodName, executionTime, Arrays.toString(args)));
        }
    }
}
